package com.invest.controller.base;

import com.google.common.collect.Lists;
import com.invest.domain.model.SystemUserDO;
import com.invest.config.WebSecurityUtils;
import com.invest.utils.type.SystemUserRoleType;
import com.invest.vo.LoginUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.Collection;
import java.util.List;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/1 Exp
 */
public abstract class BaseController {

   @ModelAttribute("user")
   //页面检索使用
    private LoginUserVO getLoginUser(){
        return WebSecurityUtils.getLoginUser();
    }

    @ModelAttribute("roles")
    public List<String> getRoles(){

        List<String> roles = Lists.newArrayList();
        User details = WebSecurityUtils.getLoginUser();
        if(details != null){
            Collection<? extends GrantedAuthority> authorities = details.getAuthorities();
            if(CollectionUtils.isNotEmpty(authorities)){
                for(GrantedAuthority item : authorities){
                    roles.add(item.getAuthority());
                }
            }
        }
        return roles;
    }
    // 当前登录的操作者
    protected SystemUserDO getOperator(){
        LoginUserVO detail = getLoginUser();
        if(detail == null){
            throw new BadCredentialsException("用户已经过期");
        }
        return detail.getSystemUserDO();

    }

    // 管理员
    protected  boolean isAdmin(){
        List<String> roles = getRoles();
        if(CollectionUtils.isEmpty(roles)){
            return false;
        }
        return roles.contains(SystemUserRoleType.SYS_ADMIN.name());

    }

    // 员工
    protected boolean isUser(){
        List<String> roles = getRoles();
        if(CollectionUtils.isEmpty(roles)){
            return false;
        }
        return roles.size() == 1 && roles.contains(SystemUserRoleType.SYS_USER.name());
    }

}